/*

* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Smart-Shop开源商城系统/ Java商城-首选电商平台系统 请务必保留此注释头信息
* |     开源地址: https://gitee.com/ningbo-qishan/gruul-mall
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     可正常分享和学习源码,未经授权 不可商用！
* |     商业版中台购买/开源版商业授权 联系技术客服
* |     官网:  https://www.73app.cn/
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Copyright (c) 2016-2999 宁波启山智软科技有限公司
* |     版权所有 ,侵权必究！
* ------------------------------------------------------------------------

*/
package com.medusa.gruul.datasets.service.impl;

import com.alibaba.fastjson.JSON;
import com.medusa.gruul.account.api.feign.RemoteMiniAccountService;
import com.medusa.gruul.common.core.exception.ServiceException;
import com.medusa.gruul.common.core.util.SystemCode;
import com.medusa.gruul.common.data.tenant.TenantContextHolder;
import com.medusa.gruul.datasets.api.constant.DataSetsMethod;
import com.medusa.gruul.datasets.api.entity.DcShopRanking;
import com.medusa.gruul.datasets.api.enums.DealingTypeEnum;
import com.medusa.gruul.datasets.mapper.DcShopRankingMapper;
import com.medusa.gruul.datasets.service.IDcShopRankingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medusa.gruul.datasets.web.model.*;
import com.medusa.gruul.goods.api.constant.GoodsProductRedisKey;
import com.medusa.gruul.goods.api.feign.RemoteGoodsService;
import com.medusa.gruul.goods.api.model.dto.manager.SkuStockDto;
import com.medusa.gruul.goods.api.model.vo.api.ApiShoppingCartProductVo;
import com.medusa.gruul.goods.api.model.vo.manager.SupplierVo;
import com.medusa.gruul.order.api.entity.OrderItem;
import com.medusa.gruul.order.api.model.OrderItemVo;
import com.medusa.gruul.order.api.model.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 交易统计表 服务实现类
 * </p>
 *
 * @author xiaoq
 * @since 2020-05-06
 */
@Service
public class DcShopRankingServiceImpl extends ServiceImpl<DcShopRankingMapper, DcShopRanking>
        implements IDcShopRankingService {

    @Autowired
    private DcShopRankingMapper dcShopRankingMapper;

    @Autowired
    private RemoteGoodsService remoteGoodsService;

    /**
     * 分析已支付完成的订单 进行分析入库 (交易量 交易额)
     *
     * @param orderVo 订单vo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderPayFinish(OrderVo orderVo) {
        TenantContextHolder.setTenantId(orderVo.getTenantId());
        Integer totalProductQuantity = 0;
        //获取订单下商品详情
        List<OrderItemVo> orderItemList = orderVo.getOrderItemList();
        DcShopRanking dcShopRanking = new DcShopRanking();
        if (orderItemList.size() > 0) {
            dcShopRanking.setShopId(orderVo.getShopId());
            dcShopRanking.setTenantId(orderVo.getTenantId());
            //遍历订单详情
            for (OrderItemVo orderItem : orderItemList) {
                //	groupLeaderInfoAdd(orderItem, orderVo);

                totalProductQuantity = orderItem.getProductQuantity() + totalProductQuantity;
                //供货商 商品排行信息取 订单商品数据
                productInfoAdd(orderItem, dcShopRanking);
                //由于供货商信息并不是必填项 对供货商信息进行判断 不为null就行插入
                if (orderItem.getProviderId() != null) {
                    dcShopRanking = new DcShopRanking();
                    String shopId = orderVo.getShopId();
                    String tenantId = orderVo.getTenantId();
                    providerInfoAdd(orderItem, dcShopRanking, shopId, tenantId);
                }
            }
        }
    }




    /**
     * 插入商品信息
     *
     * @param orderItem     订单商品信息对象
     * @param dcShopRanking 交易统计对象
     */
    private void productInfoAdd(OrderItem orderItem, DcShopRanking dcShopRanking) {
        dcShopRanking.setProductId(orderItem.getProductId());
        dcShopRanking.setTradingVolume(orderItem.getProductQuantity());
        dcShopRanking.setTradeVolume(orderItem.getProductPrice());
        BigDecimal productPrice = orderItem.getProductPrice();
        if (orderItem.getProductQuantity() > 1) {
            //当订单商品数量大于 1  商品数量 * 商品价格
            BigDecimal tradeVolume = orderItem.getProductPrice()
                    .multiply(BigDecimal.valueOf(orderItem.getProductQuantity()));
            dcShopRanking.setTradeVolume(tradeVolume);
        }
        //判断商品实售价是否等于0  等于0则走指导价
        if (productPrice.compareTo(BigDecimal.ZERO) == 0) {
            dcShopRanking.setTradeVolume(orderItem.getProductOriginalPrice());
            if (orderItem.getProductQuantity() > 1) {
                BigDecimal tradeVolume = orderItem.getProductPrice()
                        .multiply(BigDecimal.valueOf(orderItem.getProductQuantity()));
                dcShopRanking.setTradeVolume(tradeVolume);
            }
        }
        dcShopRanking.setNick(orderItem.getProductName());
        dcShopRanking.setUrl(orderItem.getProductPic());
        //插入 type值
        dcShopRanking.setType(DealingTypeEnum.PRODUCT.getCode());
        //封装年月日 yyyy  yyyyMM  yyyyMMdd
        dcShopRanking.setYyyy(DataSetsMethod.communalYyyy());
        dcShopRanking.setYyyyMM(DataSetsMethod.communalYyyyMM());
        dcShopRanking.setYyyyMMdd(DataSetsMethod.communalYyyyMMdd());

        int insert = dcShopRankingMapper.insert(dcShopRanking);
        if (insert < 1) {
            throw new ServiceException("商品信息插入失败", SystemCode.DATA_ADD_FAILED.getCode());
        }
    }


    /**
     * 插入供应商信息
     *
     * @param orderItem     订单商品信息对象
     * @param dcShopRanking 交易统计对象
     */
    private void providerInfoAdd(OrderItem orderItem, DcShopRanking dcShopRanking, String shopId, String tenantId) {
        dcShopRanking = new DcShopRanking();
        dcShopRanking.setTradingVolume(orderItem.getProductQuantity());
        dcShopRanking.setTradeVolume(orderItem.getProductPrice());
        //判断商品实售价是否等于0  等于0则走指导价
        BigDecimal productPrice = orderItem.getProductPrice();
        if (orderItem.getProductQuantity() > 1) {
            BigDecimal tradeVolume = orderItem.getProductPrice()
                    .multiply(BigDecimal.valueOf(orderItem.getProductQuantity()));
            dcShopRanking.setTradeVolume(tradeVolume);
        }
        if (productPrice.compareTo(BigDecimal.ZERO) == 0) {
            if (orderItem.getProductQuantity() > 1) {
                BigDecimal tradeVolume = orderItem.getProductPrice()
                        .multiply(BigDecimal.valueOf(orderItem.getProductQuantity()));
                dcShopRanking.setTradeVolume(tradeVolume);
            }
            dcShopRanking.setTradeVolume(orderItem.getProductOriginalPrice());
        }
        dcShopRanking.setShopId(shopId);
        dcShopRanking.setTenantId(tenantId);
        dcShopRanking.setProviderId(orderItem.getProviderId());
        dcShopRanking.setType(DealingTypeEnum.SUPPLIER.getCode());
        dcShopRanking.setYyyy(DataSetsMethod.communalYyyy());
        dcShopRanking.setYyyyMM(DataSetsMethod.communalYyyyMM());
        dcShopRanking.setYyyyMMdd(DataSetsMethod.communalYyyyMMdd());
        int insert = dcShopRankingMapper.insert(dcShopRanking);
        if (insert < 1) {
            throw new ServiceException("供货商信息插入失败", SystemCode.DATA_ADD_FAILED.getCode());
        }
    }

    /**
     * 排行榜销售量获取
     *
     * @return 城市合伙人排行榜销量 (商品  供应商)
     */
    @Override
    public RankingsVo getRankingsInfos() {
        RankingsVo rankingsVo = new RankingsVo();
        RankingsDto rankingsDto = new RankingsDto();
        GoodsProductRedisKey goodsProductRedisKey = new GoodsProductRedisKey();
        //获取当前月
        Integer month = DataSetsMethod.communalYyyyMM();
        //获取商品 交易量
        List<RankingsDto> rankingsInfos = dcShopRankingMapper.selectVBByType(DealingTypeEnum.PRODUCT.getCode(), month);
        if (rankingsInfos.size() > 0) {
            List<RankingsDto> rds = new ArrayList<>(rankingsInfos.size());
            for (RankingsDto rankingsInfo : rankingsInfos) {
                Long productId = rankingsInfo.getId();
                Integer tradingVolume = rankingsInfo.getTradingVolume();
                ApiShoppingCartProductVo apiShoppingCartProductVo = JSON
                        .parseObject(goodsProductRedisKey.get(productId.toString()), ApiShoppingCartProductVo.class);
                rankingsDto.setUrl(apiShoppingCartProductVo.getPic());
                rankingsDto.setNick(apiShoppingCartProductVo.getProductName());
                rankingsDto.setTradingVolume(tradingVolume);
                //获取商品最低价格
                BigDecimal productFloorPrice = getProductFloorPrice(apiShoppingCartProductVo);
                rankingsDto.setPrice(productFloorPrice);
                rds.add(rankingsDto);
                rankingsDto = new RankingsDto();
            }
            rankingsVo.setProductVBRanking(rds);
        }
        // 获取 供应商交易量前五
        List<RankingsDto> providerVB = getProviderVB(rankingsDto, month);
        if (providerVB.size() > 0) {
            rankingsVo.setSupplierVBRanking(providerVB);
        }
        return rankingsVo;
    }


    /**
     * 获取供应商交易数量 排行前五
     *
     * @param rankingsDto 排行榜dto
     * @param month       当前月份
     * @return 供应商交易数量排行榜前五
     */
    private List<RankingsDto> getProviderVB(RankingsDto rankingsDto, Integer month) {
        List<RankingsDto> rankingsInfos = dcShopRankingMapper.selectVBByType(DealingTypeEnum.SUPPLIER.getCode(), month);
        List<RankingsDto> rds = new ArrayList<>(rankingsInfos.size());
        if (rankingsInfos.size() > 0) {
            for (RankingsDto rankingsInfo : rankingsInfos) {
                Integer tradingVolume = rankingsInfo.getTradingVolume();
                Long providerId = rankingsInfo.getId();
                List<SupplierVo> dataSetSupplier = remoteGoodsService
                        .findDataSetSupplierList(Arrays.asList(providerId));
                if (dataSetSupplier.size() > 0) {
                    for (SupplierVo supplierVo : dataSetSupplier) {
                        rankingsDto = new RankingsDto();
                        rankingsDto.setNick(supplierVo.getName());
                        rankingsDto.setMobile(supplierVo.getMobile());
                        rankingsDto.setTradingVolume(tradingVolume);
                        rds.add(rankingsDto);
                    }
                }
            }
        }
        return rds;
    }

    /**
     * 排行榜销售额排行获取
     *
     * @return 城市合伙人 销售额排行榜 (商品  供应商)
     */
    @Override
    public RankingsGMVVo getRankingsGVMInfos() {
        RankingsGMVVo rankingsGMVVo = new RankingsGMVVo();
        RankingsDto rankingsDto = new RankingsDto();
        GoodsProductRedisKey goodsProductRedisKey = new GoodsProductRedisKey();
        Integer month = DataSetsMethod.communalYyyyMM();
        //获取商品 交易量
        List<RankingsDto> rankingsGVMDtos = dcShopRankingMapper
                .selectGVMByType(DealingTypeEnum.PRODUCT.getCode(), month);
        List<RankingsDto> rds = new ArrayList<>(rankingsGVMDtos.size());
        if (rankingsGVMDtos.size() > 0) {
            for (RankingsDto rankingsGVMDto : rankingsGVMDtos) {
                BigDecimal tradeVolume = rankingsGVMDto.getTradeVolume();
                Long productId = rankingsGVMDto.getId();
                ApiShoppingCartProductVo apiShoppingCartProductVo = JSON
                        .parseObject(goodsProductRedisKey.get(productId.toString()), ApiShoppingCartProductVo.class);
                rankingsDto.setUrl(apiShoppingCartProductVo.getPic());
                rankingsDto.setNick(apiShoppingCartProductVo.getProductName());
                rankingsDto.setTradeVolume(tradeVolume);
                //获取商品最低价格
                BigDecimal productFloorPrice = getProductFloorPrice(apiShoppingCartProductVo);
                rankingsDto.setPrice(productFloorPrice);
                rds.add(rankingsDto);
                rankingsDto = new RankingsDto();
            }
            rankingsGMVVo.setProductGMVRanking(rds);
        }
        // 获取供应商交易额排行前五
        List<RankingsDto> providerGMM = getProviderGMM(rankingsDto, month);
        if (providerGMM.size() > 0) {
            rankingsGMVVo.setSupplierGMVRanking(providerGMM);
        }

        return rankingsGMVVo;
    }



    /**
     * 获取供应商交易额 排行前五
     *
     * @param rankingsDto 排行榜dto
     * @param month       当前月份
     */
    private List<RankingsDto> getProviderGMM(RankingsDto rankingsDto, Integer month) {
        List<RankingsDto> rankingsGVMDtos = dcShopRankingMapper
                .selectGVMByType(DealingTypeEnum.SUPPLIER.getCode(), month);
        List<RankingsDto> rds = new ArrayList<>(rankingsGVMDtos.size());
        if (rankingsGVMDtos.size() > 0) {
            for (RankingsDto rankingsGVMDto : rankingsGVMDtos) {
                BigDecimal tradeVolume = rankingsGVMDto.getTradeVolume();
                Long providerId = rankingsGVMDto.getId();
                List<SupplierVo> dataSetSupplier = remoteGoodsService
                        .findDataSetSupplierList(Arrays.asList(providerId));
                if (dataSetSupplier.size() > 0) {
                    for (SupplierVo supplierVo : dataSetSupplier) {
                        rankingsDto = new RankingsDto();
                        rankingsDto.setNick(supplierVo.getName());
                        rankingsDto.setMobile(supplierVo.getMobile());
                        rankingsDto.setTradeVolume(tradeVolume);
                        rds.add(rankingsDto);
                    }
                }
            }
        }
        return rds;
    }


    /**
     * 获取商品最低价格
     *
     * @param apiShoppingCartProductVo 小程序会员购物车商品缓存信息
     * @return 单规格取当前价格  多规格取最低价
     */
    private BigDecimal getProductFloorPrice(ApiShoppingCartProductVo apiShoppingCartProductVo) {
        List<SkuStockDto> skuStocks = apiShoppingCartProductVo.getSkuStocks();
        BigDecimal price = skuStocks.get(0).getPrice();
        if (price.compareTo(BigDecimal.ZERO) == 0) {
            price = skuStocks.get(0).getOriginalPrice();
        }
        if (skuStocks.size() > 1) {
            for (int i = 0; i < skuStocks.size(); i++) {
                if (price.compareTo(skuStocks.get(i).getPrice()) == 1) {
                    price = skuStocks.get(i).getPrice();
                }
            }
        }
        return price;
    }

    /**
     * 测试 无用
     *
     * @param orderItem
     * @param dcShopRanking
     */
    @Override
    public void test(OrderItem orderItem, DcShopRanking dcShopRanking) {

    }
}

